package com.wtao.imagereader.utils;

import android.hardware.camera2.TotalCaptureResult;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TotalCaptureResultUtil {
    private static Field sTargetField;
    private static Method sTargetMethod;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static void recycle(TotalCaptureResult tcr){
            try {
                if(sTargetField==null) {
                    sTargetField = tcr.getClass().getSuperclass().getDeclaredField("mResults");
                    sTargetField.setAccessible(true);
                }
                if(sTargetMethod == null){
                    sTargetMethod = Class.forName("android.hardware.camera2.impl.CameraMetadataNative").getDeclaredMethod("close");
                    sTargetMethod.setAccessible(true);
                }
                sTargetMethod.invoke(sTargetField.get(tcr));
            } catch (NoSuchFieldException | ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }


    }
}
